<template>
   <div :class="['email-message-dialog',readonly ? 'disabled-sty' : '']">
    <!-- 邮件头信息 -->
    <div class="email-content-header">
      <!-- 触发器消息、通用消息和内部消息不展示抄送人 -->
      <div class="flex-center" v-if="!(readonly || type === 'inside') && !this.isTrigger">
        <div class="label">抄送人</div>
        <el-select
          v-model="emailTemplate.ccType"
          multiple
          placeholder="全部联系人"
          class="cc-select"
        >
          <el-option :key="0" label="全部联系人" :value="0"></el-option>
          <el-option :key="1" label="默认联系人" :value="1"></el-option>
          <!-- 只有客服中心才有事件发起人选项 -->
          <el-option v-if="module === 'event'" :key="2" label="事件发起人" :value="2"></el-option>
        </el-select>
      </div>
      <div class="flex-center">
        <div class="label label-subject">主题</div>
        <el-input v-model="emailTemplate.subject" placeholder="请输入" maxlength="50" show-word-limit></el-input>
        <div v-if="isOpenMultiLanguage" class="language-config" @click="openDialog('subject')">
          <i class="iconfont icon-earth"></i>
        </div>
      </div>
      <div class="flex-center">
        <div class="label">附件</div>
        <div class="file">
          <div class="base-comment-attachment base-file__preview file-item" v-if="emailTemplate.attachment && emailTemplate.attachment.length">
            <base-file-item v-for="(file, index) in emailTemplate.attachment" :source="emailTemplate.attachment" :key="file.id" :file="file" @delete="deleteFile(index)" size="small"></base-file-item>
          </div>
          <button type="button" class="base-comment-tool file-button" @click="chooseFile">
            <i class="iconfont icon-attachment"></i> 添加附件(50MB)
          </button>
          <input class="select-file" type="file" ref="input" @change="handleChange" multiple>
          <div class="base-comment-cover loading" v-if="!allowOperate">
            <base-spin text="请稍等..."></base-spin>
          </div>
        </div>
      </div>

    </div>

    <!-- 富文本编辑器 -->
    <div style="display:flex; align-items: flex-start;">
      <base-editor ref="editor" class="msg-email__editor" v-model="emailTemplate.content" :is-edit="true" :max-length="5000" :key="editorKey" :is-trigger="isTrigger" @input="getInput" @rangeIndex="getRangeIndex"></base-editor>
      <div v-if="isOpenMultiLanguage" class="language-config" style="width: 40px" @click="openDialog('content')">
        <i class="iconfont icon-earth"></i>
      </div>
    </div>

    <!-- 选择字段 -->
    <div class="select-modules" v-if="!readonly">
      <!-- <el-select
        v-model="selectModule"
        placeholder="选择模块"
        @change="moduleChange"
      >
        <el-option v-for="item in selectModules" :key="item.moduleValue" :label="item.moduleName" :value="item.moduleValue"></el-option>
      </el-select> -->
      <el-select
        v-model="selectField"
        :filterable="moduleType === 'task' ? true : false"
        placeholder="选择字段"
      >
        <el-option v-for="item in selectFields" :key="item.fieldValue" :label="item.fieldName" :value="item.fieldValue"></el-option>
      </el-select>
      <!-- <el-button id="create-window" type="primary" @click="addField">插入字段</el-button> -->
      <el-button type="text" class="insert-btn" @click="addField">  &lt/&gt插入字段</el-button>
      <span class="tip"> <i class="iconfont icon-info-circle"></i>点击后可在内容所在光标位置插入字段</span>
    </div>

    <MultilingualDialog
      ref="multilingualDialogRef"
      title="多语配置"
      :type="emailTemplateKey !== 'content' ? 'text' : 'textarea'"
      :is-need-validation="true"
      :language-list="languageList"
      @update="updateFields"
    />
  </div>
</template>

<script>
import Uploader from '@src/util/uploader';
import * as EmailMessageApi from '@src/api/EmailApi';
import TypeNameEnum from '@model/enum/TypeNameEnum';
import MultilingualDialog from './MultilingualDialog.vue';
import { getRootWindow } from '@src/util/dom';
import { isNotUndefined } from '@src/util/type';
import { getTaskExtendFieldList } from '@src/api/TaskApi'
import { isSubForm } from '@src/util/function';
import { allowSwitchLanguage } from '@src/util/version';

let rangeIndex = -1;

export default {
  name: 'email-message',
  inject: {
    module: { value: "module", default: null },
    flowData: { value: "flowData", default: null },
    projectData: { value: "projectData", default: null },
  },
  props: {
    sourceData: {
      type: Object,
      default: () => ({})
    },

    readonly: {
      type: Boolean,
      default: false
    },

    // 当前渠道的channel值
    channel:{
      type:[String,Number],
      required:true
    },

    // 当前选中的渠道
    sendChannelList:{
      type:Array,
      required:true
    },
    // 消息类型 inside：内部，customer：客户
    type: {
      type: String,
      required: true
    },
    // 消息模块的来源/ 客服/ 工单/ 智能报告
    moduleType: {
      type: String,
      default: '',
    },
    modules: {
      type: Array,
      default: () => []
    },
    // 是否校验模版内容变化 默认要校验 触发器不校验
    isValidateChange: {
      type: Boolean,
      default: true
    },
    // 是否是触发器
    isTrigger: {
      type: Boolean,
      default: false
    },

    // 当前的触发对象
    messageTriggerType: {
      type: String,
      default: '',
    },

    // 当前的触发对象的表单字段
    taskExtendData: {
      type: Array,
      default: (() => []),
    },
    // 是否是工单自定义节点
    isTaskCustomNode: {
      type: Boolean,
      default: false
    },
  },
  components: {
    MultilingualDialog,
  },
  computed:{
    // 加载显示
    allowOperate(){
      return !this.pending
    },
  },
  data() {
    return {
      pending: false,
      // 邮件模板
      emailTemplate: {
        messageId: '',
        typeName: '',
        receiverType: [0],
        ccType: [0],
        subject: '',
        subjectLanguage: null,
        attachment: [],
        content: '',
        contentLanguage: {},
      },
      // 选择字段
      selectModule: '',
      originModules: [],
      selectModules: [
        // { moduleName: '选择模块', moduleValue: '' }
      ],
      selectField: '',
      selectFields: [],
      languageList: [],
      isOpenMultiLanguage: false,
      emailTemplateKey: '',
      // 记录出始的数据，用于保存时比对是否有修改
      emailMsgTemplateInit:'',
      editorKey: 0,
    }
  },
  watch: {
    type: {
      handler() {
        // 消息通知切换内部外部数据初始化
        if(this.isChange()) {
          this.editorKey++
          this.$nextTick(()=>{
            this.init()
          })
        }
      }
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    async init() {
      if ((Array.isArray(this.modules) && this.modules.length) || this.isTrigger) {
        this.initialize()
        await this.templateFieldDataHandle(this.modules)
      } else {
        await this.editTemplate(this.sourceData.typeName);
      }

      // 如果是工单中心的消息设置
      if (this.moduleType === 'task') {
        this.getTaskExtendField()
      }
      
    },
    async getTaskExtendField() {
      await getTaskExtendFieldList({type: 'TASK'}).then((res) => {
        if (res.succ && res.data.fieldList?.length > 0) {
          this.selectFields = [...this.selectFields, ...res.data.fieldList]
        }
      })
    },
    getMultilingualAuth(contentLanguage) {
      const RootWindow = getRootWindow(window);
      this.languageList = RootWindow?.languages || [];
      this.isOpenMultiLanguage = (RootWindow?.grayAuth?.multiLanguage && contentLanguage) ?? false;
      // 是否允许切换语言包 老版本不限制，新版本只有国际化账号才允许切换语言包
      this.isOpenMultiLanguage = allowSwitchLanguage();
    },
    openDialog(key) {
      this.emailTemplateKey = key;
      if (this.emailTemplateKey === 'subject' && this.emailTemplate.subjectLanguage) {
        if (this.emailTemplate.subjectLanguage['zh'] !== this.emailTemplate.subject) {
          const _value = Object.assign({}, this.emailTemplate.subjectLanguage);
          _value['zh'] = this.emailTemplate.subject;
          this.$refs.multilingualDialogRef.openDialog(_value);
        } else {
          this.$refs.multilingualDialogRef.openDialog(this.emailTemplate.subjectLanguage || {});
        }
      } else if (this.emailTemplateKey === 'content' && this.emailTemplate.contentLanguage) {
        if (this.emailTemplate.contentLanguage['zh'] !== this.emailTemplate.content) {
          const _value = Object.assign({}, this.emailTemplate.contentLanguage);
          _value['zh'] = this.emailTemplate.content;
          this.$refs.multilingualDialogRef.openDialog(_value);
        } else {
          this.$refs.multilingualDialogRef.openDialog(this.emailTemplate.contentLanguage || {});
        }
      }
    },
    updateFields(value) {
      if (this.emailTemplateKey === 'subject') {
        this.emailTemplate.subjectLanguage = value;
        this.emailTemplate.subject = value?.['zh'] || '';
      } else if (this.emailTemplateKey === 'content') {
        this.emailTemplate.contentLanguage = value;
      }
    },
    // 供父组件调用，提交校验，当校验失败resolve里面传入失败原因
    validate(){
      const { ccType, subject, content } = this.emailTemplate;

      let validName = []

      !ccType.length && validName.push('抄送人');
      !subject && validName.push('邮件主题');
      !content && validName.push('邮件内容');

      // 当前渠道是否被勾选了
      const isSelected = this.sendChannelList.includes(this.channel)

      const validRes = validName.length ? `您${isSelected ? '勾选了' : '修改了'}邮件消息渠道，请先填写${validName.join('、').replace(/(.*)、/, '$1和')}` : true
      return Promise.resolve(validRes);
    },
    // 供父组件调用，是否有修改模版
    isChange(){
      return this.emailMsgTemplateInit !== JSON.stringify(this.emailTemplate)
    },
    // 供父组件调用，获取参数
    getParam(){
      const emailTemplate = this.emailTemplate;

      let params = { emailMsgTemplateParam:null}

      // 当没有修改模版，提交时emailMsgTemplateParam传null
      if(!this.isChange() && this.isValidateChange) return params

      if(emailTemplate.subjectLanguage) {
        if (emailTemplate.subjectLanguage.zh !== emailTemplate.subject) emailTemplate.subjectLanguage.zh = emailTemplate.subject;
      }
      if(params.contentLanguage) {
        if (emailTemplate.contentLanguage.zh !== emailTemplate.subject) emailTemplate.contentLanguage.zh = emailTemplate.content;
      }


      emailTemplate?.attachment?.map(item => {
        const { filename, url, fileSize } = item
        item.fileName = filename
        item.ossUrl = url
        item.fileSizeStr = fileSize
      })
      params.emailMsgTemplateParam = emailTemplate
      return params
    },
    // 编辑邮件模板
    async saveTemplate(){
      const params = this.emailTemplate;
      if(!params.subject) return this.$message.warning('请输入主题');
      if(!params.content) return this.$message.warning('请输入模板内容');

      if (params.subjectLanguage.zh !== params.subject) params.subjectLanguage.zh = params.subject;
      if (params.contentLanguage.zh !== params.content) params.contentLanguage.zh = params.content;
      try {
        const { code, message } = await EmailMessageApi.change(params);
        if (code) return this.$message.warning(message);
      } catch (error) {
        console.log(error);
      }
    },
    // 选择模块
    moduleChange(value) {
      this.selectModule = value;
      if(!value) {
        this.selectField = '';
        this.selectFields = [];
        return;
      }
      // 获取选择模块和对应的字段
      let current = null;
      for (let index = 0; index < this.selectModules.length; index++) {
        if(this.selectModules[index].moduleValue === value) {
          current = this.selectModules[index];
          break;
        }
      }
      if(!current) return this.selectFields = [];
      this.selectFields = current.fieldList || [];
    },
    // 插入字段
    addField(){

      if(!this.selectField) return this.$message.warning('请选择字段！');

      let content = this.emailTemplate.content;
      if(rangeIndex < 0) rangeIndex = content.length;
      if (content && content.indexOf(this.selectField) > -1) return this.$message.warning('该字段已存在，请勿重复添加');

      // 获取光标位置
      const selectionIndex = this.$refs.editor.getSelection();

      // 如果光标位置存在，就在光标位置插入，否则就在最后插入
      if (isNotUndefined(selectionIndex)) {
        rangeIndex = selectionIndex;
      } else {
        rangeIndex = content.length;
      }

      // 插入字段文本
      const text = ` {${this.selectField}} `
      // 插入数据
      this.$refs.editor.insertText(rangeIndex, text)
      // 获取插入后的html
      const getHtml = this.$refs.editor.getHtml();
      // 更新数据
      this.emailTemplate.content = getHtml

    },
    handleContent(str1, index, str2){
      let s1 = '';
      let s2 = '';
      if(str1.length < index) return str1 + str2;
      s1 = str1.substring(0, index);
      s2 = str1.substring(index, str1.length);
      return s1 + str2 + s2;
    },
    // 选择文件
    handleChange(event){
      const files = event.target.files;
      if(!files || !files.length) return;
      for (let index = 0; index < files.length; index++) {
        let size = files[index].size / 1024 / 1024
        if(size > 50){
          return this.$platform.alert('单个文件大小不能超过50M')
        }
      }
      this.pending = true;
      let attachments = this.emailTemplate.attachment;
      Uploader.batchUploadWithParse({files}).then(result => {
        let {success, error} = result;
        if(error.length){
          let message = error.map(item => item.message).join('\n');
          this.$platform.alert(message)
        }
        if(success.length){
          this.emailTemplate.attachment = attachments.concat(success);
        }
        // console.log('this.emailTemplate.attachments', this.emailTemplate.attachment);
      })
        .catch(err => console.error(err))
        .then(() => this.pending = false)
    },
    // 删除文件
    deleteFile(index) {
      this.emailTemplate.attachment.splice(index, 1);
    },
    chooseFile () {
      if(this.pending) return this.$platform.alert('请等待文件上传完成');
      this.$refs.input.value = null;
      this.$refs.input.click();
    },

    // 给表单字段赋值
    initFormVal(data){

      // this.emailTemplate.content = '尊敬的客户您好，我们已经安排{user}（{umobile}）处理您的服务需求，了解进度请访问{url}'
      let attachment = data.attachment;
      if(attachment && typeof attachment === 'string'){
        attachment = JSON.parse(attachment);
      }
      this.emailTemplate.attachment = attachment || [];

      this.emailTemplate.messageId = data.messageId || '';
      this.emailTemplate.typeName = data.typeName || '';
      this.emailTemplate.receiverType = data.receiverType || [];
      this.emailTemplate.ccType = data.ccType || [];
      this.emailTemplate.subject = data.subject || '';
      this.emailTemplate.subjectLanguage = data.subjectLanguage || null;
      this.emailTemplate.content = data.content || '';
      this.emailTemplate.contentLanguage = data.contentLanguage || {};

      this.getMultilingualAuth(this.emailTemplate.subjectLanguage);
    },

    // 编辑模板
    async editTemplate(typeName){
      this.title = TypeNameEnum[typeName];
      this.selectModule = '';
      this.selectField = '';

		  try {
        // const { code, data, message } = await EmailMessageApi.getTemplate({typeName});
        // if(code) return this.$message.warning(message);
        this.initFormVal(this.sourceData || {})
      } catch (error) {
        console.log(error);
      }
      !this.readonly && await this.getTemplateField(typeName);
      // 记录出始的数据，用于保存时比对是否有修改
      this.emailMsgTemplateInit = JSON.stringify(this.emailTemplate)
    },
    // 获取模板自定义字段
    async getTemplateField(template){
            // debugger
      if(this.module === 'paas') {
        this.selectModule = 'paas';
        this.selectFields = this.flowData.msgTemplateSelectFields
        return
      }

      if(this.module === 'project') {
        this.selectModule = 'project';
        if (this.messageTriggerType === 'TASK') {
          // 项目消息-任务消息列表字段处理 工单字段/通用字段
          this.selectFields = this.taskExtendData.filter(field => !isSubForm(field) && !field?.isHidden).map(item=> {
              return {
                fieldValue: item.fieldName,
                fieldName: item.displayName,
                moduleId: item.fieldName,
                moduleName: 'project'
              }
          })
          return
        }
        // 项目类型表单的字段
        return this.selectFields = this.projectData.fields
      }

      try {
        let { code, data, message } = await EmailMessageApi.getTemplateField({template: this.isTaskCustomNode ? 'TASK_NODE_NEW' : template});
        if(code) return this.$message.warning(message);
        if(!data || !data.length) data = [];

        this.templateFieldDataHandle(data)

      } catch (error) {
        console.log(error);
      }
    },
    initialize() {
      this.selectModule = '';
      this.selectField = '';

      try {
        this.initFormVal(this.sourceData || {})
      } catch (error) {
        console.error(error);
      }

      // 记录出始的数据，用于保存时比对是否有修改
      this.emailMsgTemplateInit = JSON.stringify(this.emailTemplate)

    },
    templateFieldDataHandle(data) {
      this.originModules = Object.freeze(data);
      this.selectModules = data;

      // 直接复制插入字段select
      if (Array.isArray(data) && data.length > 0)  {
        this.selectFields = data[0].fieldList
        this.selectModule = data[0].moduleValue;
      }

    },
    // 获取带格式的编辑器内容<p>xxx</p>
    getInput (html) {
      this.emailTemplate.content = html;
      return true;
    },
    getRangeIndex(index){
      rangeIndex = index;
    },
    // 关闭窗口
    closeDialog() {
      this.formStatus.editFrom = false;
    },

  },
}
</script>

<style lang="scss">
.disabled-sty {
  cursor: not-allowed;
  *{
    pointer-events: none;
  }
}
.email-message-dialog {
  padding: 20px;
  height: 100%;
  /* background: #fff; */
  .email-message-form{
    background: #fff;
    height:100%;
    padding: 16px;
    border-radius: 4px;
  }
  .flex-center {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    .label {
      width: 60px;
      height: 22px;
      font-size: 14px;
      color: #262626;
      line-height: 22px;
    }
    .label-subject {
      margin-right: 8px;
    }
    .cc-select {
      flex: 1;
      .el-tag {
        width: auto;
      }
    }
    i {
      cursor: pointer;
    }
    .select-file {
      display: none;
    }
  }
  .ql-toolbar.ql-snow {
    border: 1px solid #d9d9d9;
  }
  .ql-container.ql-snow {
    border: 1px solid #d9d9d9;
  }

  .select-modules {
    padding: 5px 8px 5px 8px;
    border-left: 1px solid #d9d9d9;
    border-right:  1px solid #d9d9d9;
    background: #fff;
    position: relative;
    clear: both;
    &::after{
      content: '';
      width: 100%;
      position: absolute;
      left: 0;
      bottom: 0;
      height: 1px;
      background: #d9d9d9;
    }
    .el-select {
      width: 190px;
      /* margin-top: 12px; */
      /* margin-right: 12px; */
    }
    .insert-btn{
      font-size: 14px;
      color: $color-primary-light-6;
      margin-left: 12px;
    }
    .tip{
      float: right;
      color: #8C8C8C;
      font-size: 12px;
      margin-top: 4px;
    }
  }
  .language-config {
    width: 36px;
    height: 32px;
    text-align: center;
    line-height: 32px;
    background: #F5F8FA;
    border-radius: 4px;
    border: 1px solid #CBD6E2;
    cursor: pointer;
    margin-left: 5px;
  }

  .email-content-header {
    .base-file-info > .base-file-info-name {
      max-width: 550px;
    }
  }
}
</style>
